package com.caldremch.calhttp.service;

import com.alibaba.fastjson.JSON;
import com.caldremch.calhttp.http.NetReqManager;
import com.caldremch.calhttp.http.api.ApiFactory;
import com.caldremch.calhttp.http.api.ApiService;
import com.caldremch.calhttp.http.base.BaseResp;
import com.caldremch.calhttp.http.base.BaseRespData;
import com.caldremch.calhttp.http.bean.BaseReq;
import com.caldremch.calhttp.http.bean.BaseReqData;
import com.caldremch.calhttp.http.callback.AbsCallback;
import com.caldremch.calhttp.http.callback.JsonObserver;
import com.caldremch.calhttp.http.callback.Tempsss;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;

/**
 * @author Caldremch
 * @date 2018-01-20 15:18
 * @describe
 **/
public class BaseApiService {


    protected static ApiService mApiService;

    static {
        mApiService = ApiFactory.getApiService();
    }

    protected static <T> void request(Observable<BaseResp> observable, RxAppCompatActivity context, AbsCallback<T> callback, BaseReqData baseReqData) {
        observable.subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .map(new Tempsss<T>()).compose(context.<BaseRespData<T>>bindToLifecycle())
                //自定义义哥带有加载框的请求 dialog
                .subscribe(new JsonObserver<T>(callback));
    }


    //获取请求体
    protected static RequestBody getReqData(BaseReqData reqObj) {
        BaseReq req = new BaseReq(reqObj);
        RequestBody requestBody
                = RequestBody.create(
                NetReqManager.MEDIA_TYPE_JSON,
                JSON.toJSONString(req));
        return requestBody;
    }

}
